package com.sevennotes.classtable.utils

import android.util.Log
import com.thegrizzlylabs.sardineandroid.DavResource
import com.thegrizzlylabs.sardineandroid.impl.OkHttpSardine
import kotlinx.coroutines.delay
import java.io.InputStream

object WebdavTool {
  var url: String = ""
  val sardine: OkHttpSardine = OkHttpSardine()

  fun initSardine(userName: String, password: String, url: String) {
    this.url = url
    sardine.setCredentials(userName, password)
  }

  fun createDirSafely(dirPath: String) {
    val dirs = dirPath.split("/")
    var path = ""
    dirs.forEachIndexed { index, name ->
      path += if (index == 0) name else "/$name"
      createDir(path)
    }
  }

  private fun createDir(dirPath: String) {
    if (!checkExist(dirPath)) {
      val path = url + dirPath
      sardine.createDirectory(path)
    }
  }

  private fun checkExist(dirPath: String): Boolean {
    val path = url + dirPath
    sardine.exists(path)
    return sardine.exists(path)
  }

  fun uploadByteArray(fileName: String, dirPath: String, data: ByteArray) {
    val fileDir = "${url}${dirPath}/$fileName"
    createDirSafely(dirPath)
    sardine.put(fileDir, data)
  }

  fun readFile(filePath: String): InputStream {
    val path = "${url}${filePath}"
    return sardine.get(path)
  }

  fun getExistFiles(filePath: String): List<DavResource> {
    val realUrl = "$url$filePath"
    if (checkExist(filePath)) {
      val list = sardine.list(realUrl)
      return list.filter { !it.isDirectory }
    }
    return emptyList()
  }

  fun deleteFile(filePath: String) {
    if (checkExist(filePath)) {
      val path = url + filePath
      sardine.delete(path)
    }
  }

  private fun getParentUrl(url: String): String {
    val index = url.lastIndexOf('/')
    return if (index == 0) {
      url
    } else {
      url.substring(0, index)
    }
  }
}